import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

import javax.jws.WebService;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@WebService(targetNamespace="http://localhost:63081/sendComplaints")
public class SendComplaintService {

	public String sendComplaints(String projectID, String differences) throws MessagingException
	{
		ComplaintsContainer cc = ComplaintsContainer.getInstance();
		HashMap<String, String> complaintsList = cc.getComplaintsList();
		Set<String> keys = complaintsList.keySet();
		for(String key : keys)
		{
			String subject = "Complaint - missing material ";

			String message = "Dear " + complaintsList.get(key) + ",\n"
					+ "We are missing " + key + ".\n"
					+ "If you have any questions, do not hesitate to contact us.\n\nKind regards,\nComnpanyXY";

			String from = "companyXY@localhost";

			sendMail("wmpm18@localhost", subject, message, from);
		}
		cc.setComplaintsList(new HashMap<String, String>());
		return "Complaints sent successfully";
	}

	private void sendMail( String recipient, String subject, String message, String from ) throws MessagingException
	{
		Properties props = new Properties();
		props.put( "mail.smtp.host", "localhost" );
		props.put("mail.smtp.port", "25");
		Session session = Session.getDefaultInstance( props );
		Message msg = new MimeMessage( session );
		InternetAddress addressFrom = new InternetAddress( from );
		msg.setFrom( addressFrom );
		InternetAddress addressTo = new InternetAddress( recipient );
		msg.setRecipient( Message.RecipientType.TO, addressTo );
		msg.setSubject( subject );
		msg.setContent( message, "text/plain" );
		Transport.send( msg );
	}
}
